package space.xxhui.javatts.base.system.exception;

import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import space.xxhui.javatts.base.constants.ProjResponseCode;
import space.xxhui.javatts.base.utils.ProjResponseUtils;
import space.xxhui.javatts.entity.ProjResponse;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author HitvzByHui
 * date 2021-03-28
 */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public ProjResponse exceptionHandler(HttpServletRequest request, Exception e){
        e.printStackTrace();
        if(e instanceof MethodArgumentNotValidException){//参数添加BindingResult，就不能抛出这个异常
            MethodArgumentNotValidException ex= (MethodArgumentNotValidException) e;
            BindingResult bindingResult = ex.getBindingResult();
            if(bindingResult.hasErrors()){
                FieldError fieldError = bindingResult.getFieldError();
                return ProjResponseUtils.error(ProjResponseCode.ARG_ERROR,"["+fieldError.getField() + "] " +fieldError.getDefaultMessage());
            }else {
                return ProjResponseUtils.error(ProjResponseCode.ARG_ERROR,"参数校验不通过"+e.getLocalizedMessage());
            }

        }else {
            return ProjResponseUtils.error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,"服务器错误"+e.getLocalizedMessage());
        }
    }

}
